#include "instance.h"



/**
 * Initialize the instance structure
 */
void initInstanceMemory(InstanceMemory* ins){
	ins -> blocReturnId = -1;
	ins -> freed = 0;
	ins -> varName[0] = '\0';	
}


void initInstance(Instance* ins){
	ins -> callerObject[0] = '\0';
	ins -> pid = -1;
	ins -> varName[0] = '\0';
	ins -> pipe[0] = -1;
	ins -> pipe[1] = -1;
	
}

void initQueue(InstanceQueue* queue){
	queue -> index = 0;
}

void printInstanceMemory(InstanceMemory instance){
	printf("Bloc id : %d\nIs free : %d\n Varname : %s",
	instance.blocReturnId,
	instance.freed,
	instance.varName
	);	
}

void printInstance(Instance instance){
	printf("Name : %s\nVarname : %s\nPid : %d\n",
	instance.callerObject,
	instance.varName,
	instance.pid
	);	
}

int existInstance(Instance ins){
	return ins.pid != -1;
}


InstanceMemory* getInstanceMemory(InstanceMemory* ins, int (*inscmp)(InstanceMemory a, InstanceMemory b)){
	int i;
	for (i = 0; i < instanceMemQueue.index; i++){
		InstanceMemory current = instanceMemQueue.queue[i];
		if (inscmp(current, *ins) == 0){
			return &(instanceMemQueue.queue[i]);	
		}
	}
	return NULL;
}

void pushInstance(InstanceQueue* queue, Instance ins){
	/*
	printf("pushInstance");	
	printInstance(ins);
	*/
	queue->instances[(queue->index)++] = ins;
}

Instance* popInstance(InstanceQueue* queue){	
	queue -> index = queue -> index - 1;
	if (queue -> index < 0) return NULL;
	Instance* ins = &(queue->instances[queue -> index]);
	return ins;
}

Instance* getInstanceFromName(InstanceQueue* queue, Instance* ins, int (*inscmp)(Instance a, Instance b)){
	int i = 0;
	Instance* returnInstance = NULL;
	for (i = 0; i < queue -> index; i++){
		Instance currentInstance = queue -> instances[i];
		if (existInstance(*ins) == 1 && inscmp(currentInstance, *ins) == 0) {
			returnInstance = &(queue -> instances[i]);
			return returnInstance;
		}
	}
	return returnInstance;
}

int compareInstanceByVarName(Instance a, Instance b){
	return strcmp(a.varName, b.varName);
}

int compareInstanceByCallerObjectName(Instance a, Instance b){
	return strcmp(a.callerObject, b.callerObject);
}

int compareInstanceByPid(Instance a, Instance b){
	return a.pid != b.pid;	
}

int compareInstanceMemByVarName(InstanceMemory a, InstanceMemory b){
	return strcmp(a.varName,b.varName);
}

int compareInstanceMemById(InstanceMemory a, InstanceMemory b){
	return a.blocReturnId != b.blocReturnId;	
}

